package com.sztx.pay.center.worker.tbschedule;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.sztx.pay.center.common.util.ConfigUtil;
import com.sztx.pay.center.common.util.Constance;
import com.sztx.pay.center.core.service.DumpDataHandleService;
import com.sztx.pay.center.dataaccess.dao.mysql.DumpRecordMysqlDAO;
import com.sztx.pay.center.dataaccess.domain.DumpRecordDO;
import com.sztx.pay.center.dataaccess.domain.OrderB2cDumpDO;
import com.sztx.pay.center.dataaccess.domain.OrderWithdrawDumpDO;
import com.sztx.se.core.tbschedule.task.BaseTask;
import com.taobao.pamirs.schedule.TaskItemDefine;
@Component("dumpWithdrawOrderTask")
public class DumpWithdrawOrderTask extends BaseTask<OrderWithdrawDumpDO> {

	@Autowired
	private DumpDataHandleService dumpDataHandleService;

	/**
	 * 未处理
	 */
	public static final Integer STATUS_UNPROCESS = 0;

	/**
	 * 处理中
	 */
	public static final Integer STATUS_PROCESSING = 1;

	/**
	 * 已处理失败
	 */
	public static final Integer STATUS_PROCESSED_FAILED = 2;

	/**
	 * 已处理成功
	 */
	public static final Integer STATUS_PROCESSED_SUCCESS = 3;

	@Autowired
	private DumpRecordMysqlDAO dumpRecordMysqlDAO;
	@Override
	public List<OrderWithdrawDumpDO> selectTasks(String taskParameter, String ownSign, int taskItemNum, List<TaskItemDefine> taskItemList, int eachFetchDataNum) throws Exception {
		if (!hasDumpRecord()) {
			log.info("没有转储统计数据,暂不进行转储!");
			return null;
		}
		List<String> taskItems = getTaskItems(taskItemList);
		List<OrderWithdrawDumpDO> logList = dumpDataHandleService.findUnHandleWithdrawOrder(taskItemNum, taskItems, eachFetchDataNum);
		return logList;
	}

	@Override
	public Object executeTask(OrderWithdrawDumpDO[] object, String ownSign) throws Exception {
		long startTime = System.currentTimeMillis();
		if (object != null) {
			boolean hasExeception = false;
			List<Integer> unHandlestatus = new ArrayList<Integer>();
			unHandlestatus.add(STATUS_UNPROCESS);
			unHandlestatus.add(STATUS_PROCESSED_FAILED);
			List<Integer> handlestatus = new ArrayList<Integer>();
			handlestatus.add(STATUS_PROCESSING);
			try {
				// 更新未处理的任务状态变为进行中
				dumpDataHandleService.batchUpdateHandleWithdrawOrder(object, unHandlestatus, STATUS_PROCESSING, 0);

				// TODO 处理任务
				dumpDataHandleService.dumpWithdrawOrder(object);
			} catch (Exception e) {
				hasExeception = true;
				log.info("转储提现订单[" + object[0].getWithdrawOrderId() + "]失败:", e);
			} finally {
				// 更新处理中的任务状态变为成功或失败，并且增加处理次数
				Integer newStatus = hasExeception ? STATUS_PROCESSED_FAILED : STATUS_PROCESSED_SUCCESS;
				dumpDataHandleService.batchUpdateHandleWithdrawOrder(object, handlestatus, newStatus, 1);
				int type = Constance.DumpRecordType.WITHDRAW.getCode();
				if (newStatus == STATUS_PROCESSED_SUCCESS) {
					dumpDataHandleService.addSuccessDumpRecordByCount(type, object.length);
				} else {
					for (OrderWithdrawDumpDO orderWithdrawDumpDO : object) {
						int executeTimes = orderWithdrawDumpDO.getExecuteTimes();
						int failedCount = 0;
						if (executeTimes == 4) {
							failedCount++;
						}
						// TODO 修改根据条数来增加
						dumpDataHandleService.addFailedDumpRecordByCount(type, failedCount);
					}
				}
				dumpDataHandleService.updateDumpRecordAddTime(type);
			}
		}
		long end = System.currentTimeMillis();
		log.info("本次提现订单处理耗时:[" + (end - startTime) + "]ms");
		return null;
	}

	@Override
	public Comparator<OrderWithdrawDumpDO> getComparator() {
		return new Comparator<OrderWithdrawDumpDO>() {
			@Override
			public int compare(OrderWithdrawDumpDO orderWithdrawDO1, OrderWithdrawDumpDO orderWithdrawDO2) {
				return orderWithdrawDO1.getWithdrawOrderId().compareTo(orderWithdrawDO2.getWithdrawOrderId());
			}

			@Override
			public boolean equals(Object obj) {
				return this == obj;
			}
		};
	}
	
	private boolean hasDumpRecord() {
		int beforeDay = ConfigUtil.dumpBeforeDay;

		Date beforeDate = getBeforeDate(new Date(), beforeDay);
		DumpRecordDO dumpRecordDO = new DumpRecordDO();
		dumpRecordDO.setDay(beforeDate);

		List<DumpRecordDO> dumpRecordDOs = dumpRecordMysqlDAO.listPageForSchedule(dumpRecordDO, null);
		if (CollectionUtils.isEmpty(dumpRecordDOs)) {
			return false;
		}
		return true;
	}
	
	private Date getBeforeDate(Date date, int beforeDay) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DAY_OF_MONTH, - beforeDay);

		return c.getTime();
	}

}
